package edu.gyc.myshop.controller;


import edu.gyc.myshop.model.Cart;
import edu.gyc.myshop.model.Goods;
import edu.gyc.myshop.model.Myuser;
import edu.gyc.myshop.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ls
 * @since 2024-02-05
 */
@Controller

public class CartController {
    @Autowired
    private CartService cartService;
    @RequestMapping("/putCart")
    public String putCart(Goods goods,  HttpSession session,Model model) {
      boolean r=  cartService.putCart(goods,  session);
        String msg = "添加购物车成功！";
        if (!r) {
            msg = "请先登录，才能购物！";
//            model.addAttribute("msg", msg);
            return "/goodsDetail?id="+goods.getId()+"&msg="+msg;
        }

        model.addAttribute("msg", msg);
//        model.addAttribute("goods", goods);
        return "/";
    }

    @RequestMapping("/myCart")
    public String myCart(HttpSession session,Model model) {

        List<Cart> carts = cartService.listCart(session);

        String msg = "尚未购买物品！";
        if (carts != null && carts.size() > 0) {
            model.addAttribute("carts", carts);
            return "/cart";
        }else{
            model.addAttribute("msg", msg);
            return "/";
        }



    }

    @RequestMapping("/deleteCart")
    public String deleteCart(Integer cartId,HttpSession session){
        Myuser user = (Myuser) session.getAttribute("user");
        if (user != null) {
            cartService.lambdaUpdate()
                    .eq(Cart::getId,cartId)
                    .remove();
        }
        return "/myCart";
    }



    @RequestMapping("/clearCart")
    public String clearCart(HttpSession session){
        Myuser user = (Myuser) session.getAttribute("user");
        if (user != null) {
            cartService.lambdaUpdate()
                    .eq(Cart::getMyuserId,user.getId())
                    .remove();
        }
        return "/myCart";
    }
}
